"""
有道翻译，直接调用js接口
"""
import requests
import params_

#请求头
#headers不能只有一个User-Agent，因为有道翻译是有一定的反扒机制的，所以我们直接全部带上
headers = {
    "Accept": "application/json, text/javascript, */*; q=0.01",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Connection": "keep-alive",
    "Content-Length": "244",
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
    "Cookie": "OUTFOX_SEARCH_USER_ID=-1506602845@10.169.0.82; JSESSIONID=aaaUggpd8kfhja1AIJYpx; OUTFOX_SEARCH_USER_ID_NCOO=108436537.92676207; ___rl__test__cookies=1597502296408",
    "Host": "fanyi.youdao.com",
    "Origin": "http://fanyi.youdao.com",
    "Referer": "http://fanyi.youdao.com/",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36",
    "X-Requested-With": "XMLHttpRequest",
}

#提交参数
def fanyi(word):
    data = params_.r(word)
    params = {
        "i": word,
        "from": "AUTO",
        "to": "AUTO",
        "smartresult": "dict",
        "client": "fanyideskweb",
        "salt": data.get('salt'),
        "sign": data.get('sign'),
        "lts": data.get('lts'),
        "bv": data.get('bv'),
        "doctype": "json",
        "version": "2.1",
        "keyfrom": "fanyi.web",
        "action": "FY_BY_REALTlME",
    }


    url = "http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"
    #发起POST请求
    response = requests.post(url=url, headers=headers, data=params).json()
    return response

print(fanyi("发起POST请求"))

